package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @package: com.hmdp.service.impl
 * @className: VoucherOrderServiceImpl
 * @author: 云溪
 * @description:
 * @date: 2025/9/10 19:39
 * @version: 1.0
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisWorker redisWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    // 创建阻塞队列
    private BlockingQueue<VoucherOrder> orderBlockingQueue = new ArrayBlockingQueue<>(1024*1024);

    // 创建消费者线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    // Bean初始化之后：打开线程执行任务
    @PostConstruct
    private void initVoucherOrderHandler() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    //代理对象
    private IVoucherOrderService proxy;

    // 使用内部类，创建消费者线程
    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            // 循环获取队列中的订单
            while (true) {
                try {
                    // 1. 获取阻塞队列中的订单
                    VoucherOrder voucherOrder = orderBlockingQueue.take();
                    // 2. 保存订单至数据库中
                    // 2.1 根据用户id获取锁
                    RLock redisLock = redissonClient.getLock("lock:order:" + voucherOrder.getUserId());
                    boolean success = redisLock.tryLock();
                    // 2.2 判断是否获取锁成功
                    if (!success) {
                        log.error("获取锁失败，请勿重复下单！");
                    }

                    try {
                        // 子线程中获取父线程的代理对象
                        proxy.createVoucherOrder(voucherOrder);
                    } finally {
                        redisLock.unlock();
                    }

                } catch (Exception e) {
                    log.error("阻塞队列拿出订单异常！");
                }
            }
        }
    }


    @Override
    public Result seckillVoucher(Long voucherId) {

        Long userId = UserHolder.getUser().getId();

        // 1. 执行Lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        int r = result.intValue();


        // 2. 判断结果是否为0
        if (r != 0) {
            // 2.1.不为0，没有购买资格
            return Result.fail(r == 1 ? "库存不足！" : "请勿重复下单！");
        }

        // 2.2.为0，有购买资格，把下单信息保存到阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        // 订单id(UUID生成)
        long orderId = redisWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 用户Id
        voucherOrder.setUserId(userId);
        // 代金券Id
        voucherOrder.setVoucherId(voucherId);

        // // 使用阻塞队列保存订单
        // orderBlockingQueue.add(voucherOrder);
        // // 在父线程中先创建好代理对象，这样事务才会生效
        // proxy = (IVoucherOrderService) AopContext.currentProxy();

        // 使用RabbitMQ，将订单存入消息队列等待异步消费
        rabbitTemplate.convertAndSend("seckill.direct","seckill.order", voucherOrder);

        // 3. 返回订单Id
        return Result.ok(orderId);
    }


    // @Override
    // public Result seckillVoucher(Long voucherId) {
    //
    //     // 1. 查询优惠券
    //     SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
    //
    //     // 2. 判断秒杀是否开始
    //     if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
    //         return Result.fail("秒杀尚未开始！");
    //     }
    //     // 3. 判断秒杀是否结束
    //     if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
    //         return Result.fail("秒杀已结束！");
    //     }
    //     // 4. 判断库存是否充足
    //     if (voucher.getStock() < 1) {
    //         return Result.fail("库存不足！");
    //     }
    //     // 5.一人一单防黄牛
    //     Long userId = UserHolder.getUser().getId();
    //
    //     // 7. 返回订单号
    //     // MySimpleRedisLock redisLock = new MySimpleRedisLock("order" + userId.toString(), stringRedisTemplate);
    //     RLock redisLock = redissonClient.getLock("lock:order:" + userId);
    //
    //     //boolean success = redisLock.tryLock(1500);
    //     boolean success = redisLock.tryLock();
    //     if (!success) {
    //         return Result.fail("请勿重复下单！");
    //     }
    //     try {
    //         // 使用AOP拿到代理对象，代理对象调用方法时，会调用代理对象对应的方法，方法内部会调用目标对象对应的方法，从而使@Transactional注解生效
    //         IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
    //         return proxy.createVoucherOrder(userId, voucherId);
    //     } finally {
    //         redisLock.unlock();
    //     }
    //
    // }

    @Override
    @Transactional
    public Result createVoucherOrder(Long userId, Long voucherId) {


        // 5.1 查询订单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        // 5.2 判断结果
        if (count > 0) {
            return Result.fail("您已购买过一次！");
        }

        // 5. 扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock-1") // set stock = stock-1
                .eq("voucher_id", voucherId).gt("stock", 0) // where stock = ? and id = ?
                .update();
        if (!success) {
            return Result.fail("库存不足！");
        }

        // 6. 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 6.1 订单Id
        long orderId = redisWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 6.2 用户Id
        voucherOrder.setUserId(userId);
        // 6.3 代金券Id
        voucherOrder.setVoucherId(voucherId);
        // 保存订单至数据库
        save(voucherOrder);

        return Result.ok(orderId);
    }

    @Override
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {

        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        // 5.1 查询订单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        // 5.2 判断结果
        if (count > 0) {
            log.error("您已购买过一次！");
        }

        // 5. 扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock-1") // set stock = stock-1
                .eq("voucher_id", voucherId).gt("stock", 0) // where stock = ? and id = ?
                .update();
        if (!success) {
            log.error("库存不足！");
        }


        // 保存订单至数据库
        save(voucherOrder);

    }


}
